package com.ll.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ll.common.to.mq.OrderTo;
import com.ll.common.utils.R;
import com.ll.common.vo.MemberEntityVo;
import com.ll.gulimall.order.constant.OrderConstant;
import com.ll.gulimall.order.entity.OrderItemEntity;
import com.ll.gulimall.order.entity.PaymentInfoEntity;
import com.ll.gulimall.order.enume.OrderStatusEnum;
import com.ll.gulimall.order.excetpion.NoStockException;
import com.ll.gulimall.order.feign.CartFeignService;
import com.ll.gulimall.order.feign.MemberFeignService;
import com.ll.gulimall.order.feign.ProductFeignService;
import com.ll.gulimall.order.feign.WareFeignService;
import com.ll.gulimall.order.interceptor.OrderInterceptor;
import com.ll.gulimall.order.service.OrderItemService;
import com.ll.gulimall.order.service.PaymentInfoService;
import com.ll.gulimall.order.to.OrderCreateTo;
import com.ll.gulimall.order.vo.*;
import com.rabbitmq.client.Channel;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.common.utils.PageUtils;
import com.ll.common.utils.Query;

import com.ll.gulimall.order.dao.OrderDao;
import com.ll.gulimall.order.entity.OrderEntity;
import com.ll.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    OrderItemService orderItemService;
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedisTemplate redisTemplate;

    ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 结算购物车
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberEntityVo memberEntityVo = OrderInterceptor.threadLocal.get();
        //获取主线程的请求头
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            //把主线程的请求头信息给副线程
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1、远程查询用户地址信息
            List<MemberAddressVo> address = memberFeignService.address(memberEntityVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //把主线程的请求头信息给副线程
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2、远程查询购物项数据
            List<CartItemVo> cartItemVos = cartFeignService.userCartItems();
            confirmVo.setItems(cartItemVos);
        }, executor).thenRunAsync(() -> {

            List<Long> skuIds = confirmVo.getItems().stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            //2、1远程查询库存
            R r = wareFeignService.hasStock(skuIds);
            List<SkuHasStock> data = r.getData(new TypeReference<List<SkuHasStock>>() {
            });
            if (data != null) {
                Map<Long, Boolean> collect = data.stream().collect(Collectors.toMap(SkuHasStock::getSkuId, SkuHasStock::getHasStock));
                confirmVo.setHasStock(collect);
            }

        }, executor);


        //3、设置用户会员级分
        confirmVo.setIntegration(memberEntityVo.getIntegration());

        //4、其他数据自动计算

        //5、orderToken TODO 接口幂等 防止重复提交
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        //设置放重令牌
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId(), token, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(memberFuture, cartFuture).get();
        return confirmVo;
    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 提交订单数据
     *
     * @param orderSubmitVo 页面提交的数据
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        OrderSubmitResponseVo responseVo = new OrderSubmitResponseVo();

        //得到用户
        MemberEntityVo memberEntityVo = OrderInterceptor.threadLocal.get();
        //1、验证令牌 0令牌失败 1删除成功 原子验证锁 删除锁
        String token = orderSubmitVo.getOrderToken();
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId()), token);
        if (result == 0L) {
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            //验证成功
            //整体流程:下单去创建订单、验令牌、验价格、锁库存
            OrderCreateTo orderTo = createOrderTo();
            //验价 绝对值小于0.01即可
            BigDecimal payAmount = orderTo.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payAmount).doubleValue()) < 0.01) { //验价成功
                //保存订单
                saveOrder(orderTo);
                //TODO 保存订单成功 调用远程服务锁定库存
                WareLockVo lock = new WareLockVo();
                lock.setOrderSn(orderTo.getOrder().getOrderSn());
                List<CartItemVo> lockItems = orderTo.getOrderItems().stream().map(item -> {
                    CartItemVo cartItemVo = new CartItemVo();
                    cartItemVo.setSkuId(item.getSkuId());
                    cartItemVo.setCount(item.getSkuQuantity());
                    return cartItemVo;
                }).collect(Collectors.toList());
                lock.setLockItems(lockItems);
                R r = wareFeignService.skuLock(lock);
                if (r.getCode() == 0) {
                    //库存锁定成功
                    responseVo.setCode(0);
                    responseVo.setOrder(orderTo.getOrder());
                    //return responseVo;
                    //TODO 发送消息MQ 订单已经创建
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderTo.getOrder());
                    return responseVo;
                } else {
                    //锁定失败
                    responseVo.setCode(3);//锁定库存失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                responseVo.setCode(2);//验价失败
                return responseVo;
            }

        }

    }

    @Override
    public void closeOrder(Message message, OrderEntity orderEntity, Channel channel) {
        Long id = orderEntity.getId();
        //查询订单
        OrderEntity order = this.getById(id);
        //查看订单状态是否可以关闭
        if (order.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            //该订单可以被关闭 修改订单状态 恢复库存
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(order);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order, orderTo);
            //发送消息恢复库存
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            System.out.println("发送消息恢复库存");
        }
        //该订单不可关闭

    }

    @Override
    public PayVo getPayOrder(String orderSn) {

        PayVo payVo = new PayVo();
        //查询该订单状态
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().
                eq("order_sn", orderSn)
                .eq("status", OrderStatusEnum.CREATE_NEW.getCode()));

        if (order == null) {
            //这订单过期了 非法订单
            return null;
        }
        payVo.setOut_trade_no(order.getOrderSn());
        //支付金额 保留两位小数 向上取整
        BigDecimal payAmount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString());
        //查询商品信息 设置商品信息
        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>());
        OrderItemEntity itemEntity = list.get(0);
        payVo.setBody(itemEntity.getSkuAttrsVals());
        payVo.setSubject(itemEntity.getSkuName());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberEntityVo memberEntityVo = OrderInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberEntityVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> orderList = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItems(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderList);

        return new PageUtils(page);


    }

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public String paySuccess(PayAsyncVo payAsyncVo) {

        //1、添加流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        infoEntity.setTotalAmount(new BigDecimal(payAsyncVo.getBuyer_pay_amount()));
        infoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        infoEntity.setCreateTime(new Date());
        infoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        infoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoService.save(infoEntity);
        //2、修改订单状态 支付成功才修改状态
        if ("TRADE_SUCCESS".equals(payAsyncVo.getTrade_status()) || "TRADE_FINISHED".equals(payAsyncVo.getTrade_status())) {
            //支付成功
            this.baseMapper.updateStatus(payAsyncVo.getOut_trade_no(), OrderStatusEnum.PAYED.getCode());
            return "success";
        }
        return "error";


    }

    private void saveOrder(OrderCreateTo orderTo) {

        OrderEntity order = orderTo.getOrder();
        this.save(order);//保存订单

        List<OrderItemEntity> orderItems = orderTo.getOrderItems();
        orderItemService.saveBatch(orderItems);//保存订单项


    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrderTo() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1、创建订单实体
        OrderEntity order = bulidOrder();
        orderCreateTo.setOrder(order);
        //2、创建订单购物项
        List<OrderItemEntity> orderItems = bulidOrderItems(order.getOrderSn());
        orderCreateTo.setOrderItems(orderItems);
        //3、计算 优惠、打折、应付、订单总金额
        calculationPrice(order, orderItems);
        return orderCreateTo;
    }

    private void calculationPrice(OrderEntity order, List<OrderItemEntity> orderItems) {
        //购物项总价
        BigDecimal total = new BigDecimal("0.0");
        //总共优惠的金额
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        if (orderItems != null && orderItems.size() > 0) {
            for (OrderItemEntity orderItem : orderItems) {
                total = total.add(orderItem.getRealAmount());
                coupon = coupon.add(orderItem.getCouponAmount());
                integration = integration.add(orderItem.getIntegrationAmount());
                promotion = promotion.add(orderItem.getPromotionAmount());
            }
        }
        //设置一些订单金额
        order.setTotalAmount(total);
        order.setCouponAmount(coupon);
        order.setIntegrationAmount(integration);
        order.setPromotionAmount(promotion);
        order.setPayAmount(total.add(order.getFreightAmount()));//应付金额
    }

    /**
     * 构建订单购物项
     *
     * @return
     */
    private List<OrderItemEntity> bulidOrderItems(String orderSn) {
        //获取购物车选中的商品
        List<CartItemVo> cartItemVos = cartFeignService.userCartItems();
        if (cartItemVos != null && cartItemVos.size() > 0) {
            List<OrderItemEntity> orderItems = cartItemVos.stream().map(item -> {
                OrderItemEntity orderItem = bulidOrderItem(item);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return orderItems;
        }
        return null;
    }

    /**
     * 构建某个购物项数据
     *
     * @param item
     * @return
     */
    private OrderItemEntity bulidOrderItem(CartItemVo item) {
        OrderItemEntity orderItem = new OrderItemEntity();
        //1、设置订单号 v
        //2、设置sku信息 v
        orderItem.setSkuId(item.getSkuId());
        orderItem.setSkuName(item.getTitle());
        orderItem.setSkuPic(item.getImgage());
        orderItem.setSkuPrice(item.getPrice());
        orderItem.setSkuQuantity(item.getCount());
        List<String> skuAttr = item.getSkuAttr();
        String saleAttr = StringUtils.collectionToDelimitedString(skuAttr, ";");
        orderItem.setSkuAttrsVals(saleAttr);
        //3、设置spu信息 远程查询 v
        R r = productFeignService.getSpuInfoBySkuId(item.getSkuId());
        SpuInfo spu = r.getData(new TypeReference<SpuInfo>() {
        });
        orderItem.setSpuId(spu.getId());
        orderItem.setSpuName(spu.getSpuName());
        orderItem.setSpuBrand(spu.getBrandId() + "");
        orderItem.setCategoryId(spu.getCatalogId());
        //4、设置优惠【可选】
        //5、设置积分
        orderItem.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        orderItem.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        //6、设置购物项优惠、打折、等其他金额
        orderItem.setIntegrationAmount(new BigDecimal("0.0"));
        orderItem.setCouponAmount(new BigDecimal("0.0"));
        orderItem.setPromotionAmount(new BigDecimal("0.0"));
        BigDecimal price = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity()));
        orderItem.setRealAmount(
                price.subtract(orderItem.getIntegrationAmount())
                        .subtract(orderItem.getCouponAmount())
                        .subtract(orderItem.getPromotionAmount())
        );//优惠后的总金额
        return orderItem;
    }

    /**
     * 构建订单 数据
     *
     * @return
     */
    private OrderEntity bulidOrder() {
        MemberEntityVo memberEntityVo = OrderInterceptor.threadLocal.get();
        //1、生成订单号
        String orderSn = IdWorker.getId() + "";
        //构建订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //远程查询收获地址 邮费
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        R r = wareFeignService.getFreight(orderSubmitVo.getAddrId());
        Fare fare = r.getData(new TypeReference<Fare>() {
        });
        //设置收货人信息
        orderEntity.setReceiverCity(fare.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fare.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fare.getAddress().getName());
        orderEntity.setReceiverPhone(fare.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fare.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fare.getAddress().getProvince());
        orderEntity.setReceiverRegion(fare.getAddress().getRegion());
        //设置邮费
        orderEntity.setFreightAmount(fare.getFare());
        //会员INfo
        orderEntity.setMemberUsername(memberEntityVo.getNickname());
        orderEntity.setMemberId(memberEntityVo.getId());
        //当前时间
        orderEntity.setCreateTime(new Date());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        return orderEntity;
    }

}